local LogonView = class("LogonView", function ()
	local logonView =  display.newLayer()
	return logonView
end)
local ExternalFun = appdf.req(appdf.EXTERNAL_SRC .. "ExternalFun")
local MultiPlatform = appdf.req(appdf.EXTERNAL_SRC .. "MultiPlatform")
local utils = appdf.req(appdf.EXTERNAL_SRC .. "Utils")


local layoutY = 10
LogonView.BT_LOGON = 1
LogonView.BT_REGISTER = 2
LogonView.CBT_RECORD = 3
LogonView.CBT_AUTO = 4
LogonView.BT_VISITOR = 5
LogonView.BT_WEIBO = 6
LogonView.BT_QQ	= 7

LogonView.BT_THIRDPARTY	= 8
LogonView.BT_WECHAT	= 9
LogonView.BT_FGPW = 10 	-- 忘记密码
LogonView.BT_SDK_LOGON = 11
LogonView.BT_CODE = 12
LogonView.BT_SDK_ACCOUNT_LOGON = 13  --账号登录
LogonView.BT_ACCOUNT_LOGON = 14

LogonView.BT_APPLE_ACCOUNT_LOGON = 15  --苹果默认账号道路 test001 123456

function LogonView:ctor(serverConfig,parent)
	print("hxh test2.1")

	print("LogonView onCreate >>>>>")
	local this = self
	self.parent = parent
	self:setContentSize(yl.WIDTH,yl.HEIGHT)
	--ExternalFun.registerTouchEvent(self)
	
	local  btcallback = function (ref, type)
		if type == ccui.TouchEventType.ended then
			ref:setScale(1)
			this:onButtonClickedEvent(ref:getTag(),ref)
		elseif type == ccui.TouchEventType.began then
			ref:setScale(yl.btscale)
			return true
		elseif type == ccui.TouchEventType.canceled then  
			ref:setScale(1)
		end
	end
	self.btcallback = btcallback
	local cbtlistener = function (sender,eventType)
		this:onSelectedEvent(sender,eventType)
		
	end
	
	local editHanlder = function ( name, sender )
		self:onEditEvent(name, sender)
	end
	

	-- ExternalFun.addArmatureWithCustomNode("BJ",self,nil,cc.p(667,228+layoutY))
	-- ExternalFun.addArmatureWithCustomNode("poker",self,nil,cc.p(667,348+layoutY))

	print("hxh test2.2")

	--账号登录
	local bg = display.newSprite("Logon/qiebg.png")
	self.bg = bg
	bg:setAnchorPoint(cc.p(0,1))
	bg:setPosition(455+18,248+40)
	bg:addTo(self)
	local zhanghaobt =  ccui.Button:create("Logon/logon_button_1.png", "Logon/logon_button_1.png", "Logon/logon_button_1.png")
--	zhanghaobt:setAnchorPoint(cc.p(0,1))
	zhanghaobt:setAnchorPoint(cc.p(0.8,0.5))
	zhanghaobt:setTag( LogonView.BT_ACCOUNT_LOGON)
	zhanghaobt:move(cc.p(775.4,260))
	zhanghaobt:setName("btn_1")
	zhanghaobt:addTo(self)
	zhanghaobt:addTouchEventListener(btcallback)
	self.zhanghaobt = zhanghaobt

	print("hxh test2.3")
		
	local lab = cc.LabelTTF:create("", "",34)
		:move(578+18,235+44)
		:setColor(cc.c3b(247,244,209))
		
	lab:setAnchorPoint(cc.p(0.5,1))
		self.lab = lab
	if GlobalUserItem.accounttype == 1 then
		lab:setString(GlobalUserItem.szAccount)
	--	lab:setString(1)
	else
		lab:setString(GlobalUserItem.dwUserID)
	--	lab:setString(1)
	end
	lab:addTo(self)


	local visitorbtn = ccui.Button:create("Logon/visitor_button_1.png", "Logon/visitor_button_1.png")
	visitorbtn:setTag(LogonView.BT_VISITOR)
	visitorbtn:move(cc.p(667, 80+60))
	visitorbtn:setName("btn_2")
	
	visitorbtn:addTouchEventListener(btcallback)
	self.visitorbtn = visitorbtn
	visitorbtn:addTo(self)
	self.m_serverConfig = serverConfig or {}
--帮助
	local youkebtn =  ccui.Button:create("Logon/youkebtn.png", "Logon/youkebtn.png", "Logon/youkebtn.png")
	youkebtn:setTag( LogonView.BT_VISITOR)
	youkebtn:move(display.width-100,60)
	youkebtn:addTo(self)
	youkebtn:addTouchEventListener(btcallback)
	self.youkebtn = youkebtn

	
	-- 添加新年图片 by djy
	-- local newyear_loadbg = ccui.ImageView:create("newyear/newyear_loadbg.png")
    -- newyear_loadbg:setPosition(cc.p(display.width/2,display.height/2))
    -- newyear_loadbg:addTo(self)
	
end

function LogonView:showLoninViewBtn( bshow )
	self.visitorbtn:setVisible(bshow)
	self.zhanghaobt:setVisible(bshow)
	self.lab:setVisible(bshow)
	self.bg:setVisible(bshow)
	self.youkebtn:setVisible(bshow)
end

function  LogonView:onReLoadUser( ... )
	-- body
end

function LogonView:onEditEvent(name, editbox)
	--print(name)
	-- if "changed" == name then
	-- 	if editbox:getText() ~= GlobalUserItem.szAccount then
	-- 		self.edit_Password:setText("")
	-- 	end
	-- end
	if device.platform == "ios" then 
		editbox:setText(editbox:getText())
	end
	
end

function LogonView:savePwdAndAount()
	if self.edit_Account then
		local accountstr = self.edit_Account:getText()
		if not accountstr or accountstr == "" then
			GlobalUserItem.accounttype = 0
		else
			GlobalUserItem.szAccount = self.edit_Account:getText()
			GlobalUserItem.szPassword = md5(md5("&^axG2"..self.edit_code:getText().."!!@##"))
			GlobalUserItem.accounttype = 1
		end
		
		
		local accountinfo = GlobalUserItem.getAccountInfo()
		if accountinfo.account ~= GlobalUserItem.szAccount then
		 local fileUtil = cc.FileUtils:getInstance()
		 if device.platform ~= "windows" then
            fileUtil:removeFile(device.writablePath.."UserDefault.xml")
        end
        fileUtil:removeFile(device.writablePath .."myMail.txt")
        fileUtil:removeFile(device.writablePath.."kefuFeedback.txt")
        fileUtil:removeFile(device.writablePath.."user_gameconfig.plist")
		fileUtil:removeFile(device.writablePath .."noticeMail.txt")
		
		cc.UserDefault:getInstance():setStringForKey("freegoldDay",0)
		cc.UserDefault:getInstance():setIntegerForKey("mymailMaxIdx",0)
		cc.UserDefault:getInstance():setIntegerForKey("kefuMaxIdx",0)
		cc.UserDefault:getInstance():setBoolForKey("getBindMoreByIp",false)
		cc.UserDefault:getInstance():setBoolForKey("getBindQMByIp",false)
		end
	end

end
function LogonView:checkInput()

	local accountinput  = self.edit_Account:getText()
	if accountinput == "" then
		showToast(self,"请输入您的游戏账号",2)
		return
	end
	local accountinput  = self.edit_code:getText()
	if accountinput == "" then
		showToast(self,"请输入您的游戏密码",2)
		return
	end

	return  true
end

function LogonView:onButtonClickedEvent(tag,ref)
	if tag == LogonView.BT_REGISTER then
		GlobalUserItem.bVisitor = false
		self:getParent():getParent():onShowRegister()
	elseif LogonView.BT_APPLE_ACCOUNT_LOGON == tag then
		GlobalUserItem.bVisitor = false
		self:getParent():getParent():onVisitor()
	elseif tag == LogonView.BT_SDK_LOGON then
		GlobalUserItem.bVisitor = false
		local accountstr = self.edit_Account:getText()
		local codestr = self.edit_code:getText()
		if accountstr == "" then
			showToast(self,"游戏账号为您注册的手机号码",2)
			return
		end
		if codestr == "" then
			showToast(self,"请输入密码",2)
			return
		end
		GlobalUserItem.bNoAutoLogon = true
		self:getParent():getParent():onLogon(self.edit_Account:getText(),md5(md5("&^axG2"..self.edit_code:getText().."!!@##")))
															
	elseif tag == LogonView.BT_CODE then
		self:getParent():getParent():onSDKCode(self.edit_Account:getText())
	elseif tag == LogonView.BT_VISITOR then
		self:getParent():getParent():onVisitor()
	elseif tag == LogonView.BT_LOGON then
		self:showBindLayer()
	elseif tag == LogonView.BT_ACCOUNT_LOGON then
        self:initloginAccountCsb()
	elseif tag == LogonView.BT_SDK_ACCOUNT_LOGON then
		if self:checkInput() then
			self:getParent():getParent():onSDKLogon(1,self.edit_Account:getText(),self.edit_code:getText())
		end
	elseif tag == LogonView.BT_THIRDPARTY then
		self.m_spThirdParty:setVisible(true)
	elseif tag == LogonView.BT_WECHAT then
		--平台判定
		local targetPlatform = cc.Application:getInstance():getTargetPlatform()
		if (cc.PLATFORM_OS_IPHONE == targetPlatform) or (cc.PLATFORM_OS_IPAD == targetPlatform) or (cc.PLATFORM_OS_ANDROID == targetPlatform) then
			self:getParent():getParent():thirdPartyLogin(yl.ThirdParty.WECHAT)
		else
			showToast(self, "不支持的登录平台 ==> " .. targetPlatform, 2)
		end
	elseif tag == LogonView.BT_FGPW then
		MultiPlatform:getInstance():openBrowser(yl.HTTP_URL .. "/Mobile/RetrievePassword.aspx")
	end
end

function LogonView:initloginAccountCsb()
	 self.schedulerID = nil
	local scheduler = cc.Director:getInstance():getScheduler()  
	if not tolua.isnull(self.rootLayer) then
		self.rootLayer:removeSelf()
	end
	local rootLayer, csbNode = ExternalFun.loadRootCSB("Logon/loginLayer.csb", self)
	rootLayer:setAnchorPoint(cc.p(0.5,0.5))

    rootLayer:move(yl.WIDTH/2,yl.HEIGHT/2)
    self.rootLayer = rootLayer
      --Top返回

    local closebt = csbNode:getChildByName("closebt")
	closebt:addTouchEventListener(function (ref,type)
        if type == ccui.TouchEventType.ended then
			ref:setScale(1)
			self.edit_Account = nil
			self.edit_code = nil
			self.edit_forget_phone = nil
			self.edit_forget_code = nil
			self.edit_forget_pwd = nil
			self.edit_forget_repwd = nil
			self.parent._szAccount = nil
			self.parent._szPassword =  nil
            rootLayer:runAction(cc.RemoveSelf:create(true))
		elseif type == ccui.TouchEventType.began then
			ref:setScale(yl.btscale)
			return true
		elseif type == ccui.TouchEventType.canceled then  
			ref:setScale(1)
            
        end
	end)

	local editHanlder = function ( name, sender )
		--self:onEditEvent(name, sender)
	end
	self.loginPanel = csbNode:getChildByName("loginbg") 
	ExternalFun.playOpenLayerAnimation( rootLayer )
	local offsety = (display.height-750)/4
	ExternalFun.FixCenterPosY(self.loginPanel,nil,nil,nil,offsety)
	self.forgetbg = csbNode:getChildByName("forgetbg")
	ExternalFun.FixCenterPosY(self.forgetbg,nil,nil,nil,offsety)
	ExternalFun.FixCenterPosY(closebt,nil,nil,nil,offsety)
	self.loginPanel:setVisible(true)
	self.forgetbg:setVisible(false)
    	--登录按钮
	self.loginPanel:getChildByName("Button_ok")
	:setTag(LogonView.BT_SDK_LOGON)
	:addTouchEventListener(self.btcallback)

	--账号输入
	local tempphone = self.loginPanel:getChildByName("tempphone") 
	self.edit_Account = ccui.EditBox:create(tempphone:getContentSize(), ccui.Scale9Sprite:create(""))
		:setPosition(tempphone:getPosition())
		:setAnchorPoint(cc.p(0.5,0.5))
		:setFontSize(tempphone:getFontSize())
		:setMaxLength(11)
		:setPlaceHolder("请输入账号")
		
		self.edit_Account:addTo(self.loginPanel)
		self.edit_Account:registerScriptEditBoxHandler(editHanlder)
	tempphone:removeFromParent()


	--密码	
	tempphone = self.loginPanel:getChildByName("temppwd") 
	self.edit_code = ccui.EditBox:create(tempphone:getContentSize(), ccui.Scale9Sprite:create(""))
		:setPosition(tempphone:getPosition())
		:setAnchorPoint(cc.p(0.5,0.5))
	--	:setFontName("fonts/round_body.ttf")
	--	:setPlaceholderFontName("fonts/round_body.ttf")
		:setFontSize(tempphone:getFontSize())
		--:setPlaceholderFontSize(24)
		:setMaxLength(12)
	--	:setFontColor(cc.c3b(204,172,139))
	--	:setPlaceholderFontColor(cc.c3b(204,172,139))
		:setInputFlag(cc.EDITBOX_INPUT_FLAG_PASSWORD)
		:setPlaceHolder("请输入密码")
		
		self.edit_code:addTo(self.loginPanel)
		self.edit_code:registerScriptEditBoxHandler(editHanlder)
-----------------------找回密码 
		tempphone:removeFromParent()
	--手机号	
	tempphone = self.forgetbg:getChildByName("TextField_phone") 
	self.edit_forget_phone = ccui.EditBox:create(tempphone:getContentSize(), ccui.Scale9Sprite:create(""))
		:setPosition(tempphone:getPosition())
		:setAnchorPoint(cc.p(0.5,0.5))
		--:setFontName("fonts/round_body.ttf")
		--:setPlaceholderFontName("fonts/round_body.ttf")
		:setFontSize(tempphone:getFontSize())
	--	:setPlaceholderFontSize(27)
	--	:setFontColor(cc.c3b(204,172,139))
	--	:setPlaceholderFontColor(cc.c3b(204,172,139))
		:setInputMode(cc.EDITBOX_INPUT_MODE_NUMERIC)
		:setMaxLength(11)
		:setPlaceHolder("请输入手机号码")
		
		self.edit_forget_phone:addTo(self.forgetbg)
		self.edit_forget_phone:registerScriptEditBoxHandler(editHanlder)
		tempphone:removeFromParent()
			--验证码	
		tempphone = self.forgetbg:getChildByName("TextField_code") 
	self.edit_forget_code = ccui.EditBox:create(tempphone:getContentSize(), ccui.Scale9Sprite:create(""))
		:setPosition(tempphone:getPosition())
		:setAnchorPoint(cc.p(0.5,0.5))
	--	:setFontName("fonts/round_body.ttf")
	--	:setPlaceholderFontName("fonts/round_body.ttf")
		:setFontSize(tempphone:getFontSize())
	--	:setFontColor(cc.c3b(204,172,139))
	--	:setPlaceholderFontColor(cc.c3b(204,172,139))
		--:setPlaceholderFontSize(27)
		:setInputMode(cc.EDITBOX_INPUT_MODE_NUMERIC)
		:setMaxLength(8)
		:setPlaceHolder("请输入验证码")
		
		self.edit_forget_code:addTo(self.forgetbg)
		self.edit_forget_code:registerScriptEditBoxHandler(editHanlder)
		tempphone:removeFromParent()
		--新密码	
		tempphone = self.forgetbg:getChildByName("TextField_pwd") 
	self.edit_forget_pwd = ccui.EditBox:create(tempphone:getContentSize(), ccui.Scale9Sprite:create(""))
		:setPosition(tempphone:getPosition())
		:setAnchorPoint(cc.p(0.5,0.5))
	--	:setFontName("fonts/round_body.ttf")
	--	:setPlaceholderFontName("fonts/round_body.ttf")
		:setFontSize(tempphone:getFontSize())
	--	:setFontColor(cc.c3b(204,172,139))
	--	:setPlaceholderFontColor(cc.c3b(204,172,139))
	--	:setPlaceholderFontSize(27)
		--:setInputMode(cc.EDITBOX_INPUT_MODE_NUMERIC)
		:setInputFlag(cc.EDITBOX_INPUT_FLAG_PASSWORD)
		:setMaxLength(12)
		:setPlaceHolder("请输入6-12位字符")
		
		self.edit_forget_pwd:addTo(self.forgetbg)
		self.edit_forget_pwd:registerScriptEditBoxHandler(editHanlder)
		tempphone:removeFromParent()
	--确认新密码	
	tempphone = self.forgetbg:getChildByName("TextField_repwd") 
	self.edit_forget_repwd = ccui.EditBox:create(tempphone:getContentSize(), ccui.Scale9Sprite:create(""))
		:setPosition(tempphone:getPosition())
		:setAnchorPoint(cc.p(0.5,0.5))
	--	:setFontName("fonts/round_body.ttf")
	--	:setPlaceholderFontName("fonts/round_body.ttf")
		:setFontSize(tempphone:getFontSize())
	--	:setFontColor(cc.c3b(255,255,255))
	--	:setPlaceholderFontColor(cc.c3b(204,172,139))
	--	:setPlaceholderFontSize(27)
		:setInputFlag(cc.EDITBOX_INPUT_FLAG_PASSWORD)
		--:setInputMode(cc.EDITBOX_INPUT_MODE_NUMERIC)
		:setMaxLength(12)
		:setPlaceHolder("请输入6-12位字符")
		tempphone:removeFromParent()
		
		
		self.edit_forget_repwd:addTo(self.forgetbg)
		self.edit_forget_repwd:registerScriptEditBoxHandler(editHanlder)
		
		local forgetButton_ok =  self.forgetbg:getChildByName("Button_ok")  --确认找回密码
		forgetButton_ok:addTouchEventListener( function(ref, type)
			if type == ccui.TouchEventType.ended then
			local AccountStr = string.gsub(self.edit_forget_phone:getText()," ","")
			local inputPWDStr = string.gsub(self.edit_forget_pwd:getText()," ","")
			local inputRePWDStr = string.gsub(self.edit_forget_repwd:getText()," ","")
			local autocodeStr = string.gsub(self.edit_forget_code:getText()," ","")
		
			if autocodeStr == "" or AccountStr == "" then
				showToast(self,"手机号或验证码不能为空或空格",1)
				return
			end

			if  string.len(AccountStr) ~= 11 then
				showToast(self,"手机号长度错误",1)
				return
			end
			local pos = string.find(AccountStr,"1")
			if  not pos or pos ~= 1 then
				showToast(self,"手机号码错误",1)
				return
			end

			if inputPWDStr == "" or inputRePWDStr == "" then
				showToast(self,"密码不能为空或空格",2)
				return
			end

			if inputPWDStr ~= inputRePWDStr then
				showToast(self,"与确认密码不一致",2)
				return
			end
			if string.len(inputPWDStr) < 6 or string.len(inputPWDStr)> 12 then
				showToast(self,"密码长度不能少于6位或多于12位",2)
				return
			end

			local function cb(code,msg)
				if msg then
					showToast(self,msg,1)
				end
				if code == 0  then
					self.loginPanel:setVisible(true)
					self.forgetbg:setVisible(false)
					GlobalUserItem.szLoginPassword = inputPWDStr
					GlobalUserItem.szPassword = inputPWDStr
					self.edit_Account:setText(AccountStr)
					self.edit_code:setText(inputPWDStr)

					-- cc.UserDefault:getInstance():setStringForKey("pwd",md5(md5("&^axG2"..inputPWDStr.."!!@##")))
					GlobalUserItem.szPassword = md5(md5("&^axG2"..inputPWDStr.."!!@##"))
					GlobalUserItem.onSaveAccountConfig()

					performWithDelay(self,function ()
						self:onButtonClickedEvent(LogonView.BT_SDK_LOGON,self.loginPanel:getChildByName("Button_ok"))
					end,0.2)

				end
			end
			local postjson = {}
			postjson.pwd = md5(md5("&^axG2"..inputPWDStr.."!!@##"))
			postjson.repwd = md5(md5("&^axG2"..inputRePWDStr.."!!@##"))
			postjson.userid = ""
			postjson.channelid = appdf.channelId
			postjson.phone = AccountStr
			postjson.verify  = autocodeStr 
			postjson.vidx=self.codeidx
			postjson.verifycode = self.verifycode
			ref:setScale(1)
			utils.forgetPWD(postjson,cb)
		elseif type == ccui.TouchEventType.began then
			ref:setScale(yl.btscale)
			return true
		elseif type == ccui.TouchEventType.canceled then  
			ref:setScale(1)
		end
		end)
		
		local getCodebt =  self.loginPanel:getChildByName("forgetBt")
			getCodebt:addTouchEventListener( function(ref, type)
			if type == ccui.TouchEventType.ended then
				self.loginPanel:setVisible(false)
			    self.forgetbg:setVisible(true)
				ref:setScale(1)
			elseif type == ccui.TouchEventType.began then
				ref:setScale(yl.btscale)
				return true
			elseif type == ccui.TouchEventType.canceled then  
				ref:setScale(1)
			end
		
				
		end)
			self.forgetbg:getChildByName("getcode"):addTouchEventListener( function(ref, type)
		if type == ccui.TouchEventType.ended then
			
			
			local AccountStr = string.gsub(self.edit_forget_phone:getText()," ","")

			if AccountStr == "" then
				showToast(self,"手机号不能为空或空格",1)
				return
			end

			if  string.len(AccountStr) ~= 11 then
				showToast(self,"手机号长度错误",1)
				return
			end
			local pos = string.find(AccountStr,"1")
			if  not pos or pos ~= 1 then
				showToast(self,"手机号码错误",1)
				return
			end

		
            ref:setEnabled(false)
            local sec = 60
            ref:setTitleText("重发（" .. sec .. "）")

		   local autoCodecb = function(code,idx,verifycode,msg)
				self.codeidx = idx
				self.verifycode = verifycode
				showToast(self,msg or "发送失败",1)
			end



			
            local verityjson = {}
			verityjson.phone = AccountStr
			verityjson.userid = ""
			verityjson.channelid = appdf.channelId
            utils.getVerityCode(verityjson,autoCodecb )
            self.schedulerID = scheduler:scheduleScriptFunc( function()
                sec = sec - 1
                if not tolua.isnull(ref) then
                    ref:setTitleText("重发（" .. sec .. "）")
                    if sec <= 0 then
                        cc.Director:getInstance():getScheduler():unscheduleScriptEntry(self.schedulerID)
                        ref:setEnabled(true)
                        ref:setTitleText("获取验证码")
                    end        
                end      
            end , 1, false)
			ref:setScale(1)
		elseif type == ccui.TouchEventType.began then
			ref:setScale(yl.btscale)
			return true
		elseif type == ccui.TouchEventType.canceled then  
			ref:setScale(1)
        end
    end )
end

function LogonView:onTouchBegan(touch, event)
	return self:isVisible()
end

function LogonView:onTouchEnded(touch, event)
	local pos = touch:getLocation();
	local m_spBg = self.m_spThirdParty
	pos = m_spBg:convertToNodeSpace(pos)
	local rec = cc.rect(0, 0, m_spBg:getContentSize().width, m_spBg:getContentSize().height)
	if false == cc.rectContainsPoint(rec, pos) then
		self.m_spThirdParty:setVisible(false)
	end
end

function LogonView:onExit()
	LogonView.super.onExit(self)
end

return LogonView